package com.iwunu.gateway.service;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.query.QueryUtils;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

/**
 * @author kinfeng
 * @date 2019/6/13 2:22 PM
 * @description
 */
@Service
public class JpaService {

    @Resource
    private EntityManager em;
    /**
     * 获取列表
     * @param sql
     * @param params
     * @return
     */
    public <T> List<T> list(String sql, Map<String, Object> params) {
        //String hql = "select o.uuid,o.name from UserModel o where 1=1 and o.uuid=:uuid";
        Query query = em.createQuery(sql);
        if (params != null) {
            for (String key : params.keySet()) {
                query.setParameter(key, params.get(key));
            }
        }
        return query.getResultList();
    }

    public <T> List<T> findListByNativeSql(String sql, Class<T> clzss) {
        return em.createNativeQuery(sql, clzss).getResultList();
    }

    /**
     * 获取分页数据
     * @param sql
     * @param params
     * @param pageable
     * @param requiredType
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> Page<T> page(String sql,Map<String, Object> params,Pageable pageable,Class<T> requiredType) {
        Query query = em.createQuery(sql);
        if (params != null) {
            for (String key : params.keySet()) {
                query.setParameter(key, params.get(key));
            }
        }
        if (pageable.isPaged()) {
            query.setFirstResult((int) pageable.getOffset());
            query.setMaxResults(pageable.getPageSize());
        }
        /**
         * 生成获取总数的sql
         */
        TypedQuery<Long> cQuery = (TypedQuery<Long>) em.createQuery(QueryUtils.createCountQueryFor(sql));
        return PageableExecutionUtils.getPage(query.getResultList(), pageable, ()->executeCountQuery(cQuery));
        //return new PageImpl<T>(query.getResultList(), pageable, executeCountQuery(cQuery));
    }
    /**
     * Executes a count query and transparently sums up all values returned.
     *
     * @param query must not be {@literal null}.
     * @return
     */
    private static Long executeCountQuery(TypedQuery<Long> query) {
        Assert.notNull(query, "TypedQuery must not be null!");
        List<Long> totals = query.getResultList();
        Long total = 0L;
        for (Long element : totals) {
            total += element == null ? 0 : element;
        }
        return total;
    }

    @Transactional
    public void save(Object object){
        em.persist(object);
        em.flush();
    }

    @Transactional
    public void update(Object object){
        em.merge(object);
        em.flush();
    }


    @Transactional
    public <T> void delete(Class<T> clazz,Object object){
        em.remove(findById(clazz,object));
        em.flush();
    }

    public <T> T findById(Class<T> clazz,Object id){
        return em.find(clazz,id);
    }

}
